package me.mononin.common.common.app;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;

import me.mononin.common.R;
import me.mononin.common.factory.presenter.BaseContract;

public  abstract class PresenterToolbarActivity <Presenter extends BaseContract.Presenter>
        extends ToolbarActivity implements BaseContract.View<Presenter>{

    protected Presenter mPresenter;
    protected ProgressDialog mLoadingDialog;

    @Override
    protected void initBefore() {
        super.initBefore();
        //控件初始化之前初始化presenter
        initPresenter();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter!=null){
            mPresenter.destroy();
        }
    }

    @Override
    public void showError(int str) {

        // 不管你怎么样，我先隐藏我
        hideDialogLoading();

        // 显示错误, 优先使用占位布局
        if (mPlaceHolderView != null) {
            mPlaceHolderView.triggerError(str);
        } else {
            Application.showToast(str);
        }
    }

    @Override
    public void showLoading() {
        if (mPlaceHolderView != null) {
            mPlaceHolderView.triggerLoading();
        }else {
            ProgressDialog dialog = mLoadingDialog;
            if (dialog==null){
                dialog = new ProgressDialog(this);
                //不可触摸取消
                dialog.setCanceledOnTouchOutside(false);
                //可强行关闭
                dialog.setCancelable(true);
                //取消操作监听
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        //取消loading直接关闭activity
                        finish();
                    }
                });
                mLoadingDialog = dialog;
            }
            dialog.setMessage(getText(R.string.prompt_loading));
            dialog.show();
        }
    }

    protected void hideDialogLoading(){
        ProgressDialog dialog = mLoadingDialog;
        if (dialog!=null){
            mLoadingDialog = null;
            dialog.dismiss();
        }
    }

    protected void hideLoading() {
        // 不管你怎么样，我先隐藏我
        hideDialogLoading();
        if (mPlaceHolderView != null) {
            mPlaceHolderView.triggerOk();
        }
    }
    @Override
    public void setPresenter(Presenter presenter) {
        mPresenter = presenter;
    }
    //初始化Presenter
    protected abstract Presenter initPresenter();
}
